/**
 * Copyright (c) 2011 TLOSS. All rights reserved.
 * Created on Aug 12, 2011
 * File name : ServletDispatcher.java
 * Package com.tloss.uweb
 */
package com.tloss.uweb;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author tungt
 * 
 */
public class ServletDispatcher extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1639701387979826998L;

	List<UrlHandler> listHandlers;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		process(req, resp);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		process(req, resp);
	}

	public void process(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if (listHandlers != null && listHandlers.size() > 0) {
			int index = -1;
			for (int i = 0; i < listHandlers.size() && index == -1; i++) {
				if (listHandlers.get(i) != null
						&& listHandlers.get(i).isValidUrl(req)) {
					index = i;
				}
			}
			if (index == -1) {
				throw new ServletException(new UrlHandlerException(
						"URL is invalid format!"));
			} else {
				listHandlers.get(index).service(req);
			}
		} else {
			throw new ServletException(new Exception(
					"listHandlers must be not null!"));
		}
	}
}
